package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    //新增菜品和口味(两个表的操作)
    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        //将客户端传回的信息进行拷贝
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //向菜品表插入数据
        dishMapper.insert(dish);

        //获取insert语句生成的主键值,用做于下一步口味的id值
        Long dishId = dish.getId();

        //把口味封装到集合中
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if(flavors !=null && flavors.size() >0){
            //将获取的主键值通过Lambda表达式遍历到flavors的id值中
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });

            //向口味表插入数据,如果客户选择口味不为空并且大于0则插入n条信息
            dishFlavorMapper.insertBatch(flavors);
        }


    }


    //分页查询
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO){
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page= dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //批量删除菜品
    @Override
    public void delete(List<Long> ids) {
        //起售中的菜品不能删除,通过集合中id循环查询有没有起售中的商品
        for (Long id : ids) {
             Dish dish=dishMapper.getById(id);
             if(dish.getStatus()== StatusConstant.ENABLE){
                 //如果为1就是起售不能删除,抛起售异常
                 throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
             }
        }

        //被套餐关联的菜品不能删除,通过ids查询套餐中有没有关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds !=null && setmealIds.size()>0){
            //当套餐中关联了就报异常("当前菜品关联了套餐,不能删除")
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

          //通过for循环性能会降低
        //删除菜品表中的菜品数据
        for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除菜品关联的口味数据
            dishFlavorMapper.deleteByDishId(id);
        }

        //根据id删除菜品表中的菜品数据
        //dishMapper.deleteByIds(ids);
        //删除菜品关联的口味数据
        //dishFlavorMapper.deleteByDishIds(ids);
    }

    //根据id查询菜品和对应的口味用于修改数据
    @Override
    public DishVO getByIdAndFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish= dishMapper.getById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors=dishFlavorMapper.getByDishId(id);
        //将查询的两条数据封装到VO中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);//把查到的口味添加进去

        return dishVO;
    }

    //修改,对菜品表和口味表的修改(可以删除,添加,或修改口味)
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //修改菜品表信息
        dishMapper.update(dish);

        //将原本的口味全删了然后再根据传回的数据插入口味(这样就不用进行判断有无该口味)
        //删除(用前面删除的mapper就行)
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //插入(先获取口味的id)
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if(flavors !=null && flavors.size() >0) {
            //将获取的主键值通过Lambda表达式遍历到flavors的id值中
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    //修改状态,停售需要把套餐也停了
    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish=new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
